package com.common.base.http.main

import android.text.TextUtils
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.common.base.http.impl.utils.NullOnEmptyConverterFactory
import com.common.base.http.impl.utils.RxSchedulers
import com.common.base.http.impl.utils.Rxlifecycle
import com.common.base.manager.ConfigManager
import com.common.base.manager.StackManager
import io.reactivex.Flowable
import org.reactivestreams.Subscriber
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by zsf on 2022/8/16 19:46
 * ******************************************
 * *
 * ******************************************
 */
object HttpManager {
    // 转换的工具
    var gson: Gson =
        GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create()


    fun build(host: String="") = initRetrofit(host)


    private fun initRetrofit(host: String): Retrofit {
        return Retrofit.Builder()
            .client(ApiOkhttpClient.getClient())
            .addConverterFactory(NullOnEmptyConverterFactory())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(
                if (TextUtils.isEmpty(host)) {
                    ConfigManager.configBean?.baseUrl?:""
                } else {
                    host
                }
            )
            .build()
    }

}

/**
 * 绑定生命周期,获取结果
 * @param observer 回调
 * @param owner 当前网路请求需要绑定的activity
 * @param untilEvent 执行监听的生命周期
 */
fun <R> Flowable<R>.execute(
    observer: Subscriber<in R?> = object : ApiSubscriber<R>() {},
    owner: LifecycleOwner = StackManager.getActivityManager().currentActivity(),
    untilEvent: Lifecycle.Event = Lifecycle.Event.ON_DESTROY
) {
    this.compose(RxSchedulers.io_main())
        .`as`(Rxlifecycle.bind(owner, untilEvent))
        .subscribe(observer)
}

